<template>
    <view class="d-kuan d-juzhong">
        <uv-overlay :show="url_data_show" @tap="url_close_get" zIndex="998" opacity="0.5">
            <view class="warp_url">
                <view class="rect_url" @tap.stop.prevent>
                    <view class="d-kuan ">
						<view class="d-kuan d-zhuangtai-left">
						    <uv-cell icon="attach" title="添加链接"></uv-cell>
						</view>
                        <view class="d-shang-10 d-kuan ">
                            <view class="d-neikuang-10 ">
								<view class="d-kuan d-wenzi-14 d-xia-10">
									<view class="d-zuo"></view>
									<view class="d-you" @click="url_tianjia">+添加</view>
								</view>
                                <view class="d-clear d-shang-10"></view>
                                <!-- 动态渲染url组 -->
                                <view class="d-kuan " id="d-gundong">
                                    <view 
										v-for="(item, index) in url_data_add" 
										:key="index"
										class="d-kuan d-yuanjiao-10 mb-10" 
										:id="'chuangyeji_id_' + index" 
										style="background-color: #f5f5f5; margin-bottom: 10px;"
										>
                                        <view class="d-neikuang-10">
                                            <view class="d-kuan d-wenzi-14">
                                                <view class="d-zuo">{{'第' + (index + 1) + '组'}}</view>
                                                <view class="d-you" @click="url_shanchu(index)">-删除</view>
                                            </view>
                                            <view class="d-clear"></view>
                                            <uv-input placeholder="名称" class="d-shang-10"  border="surround" v-model="item.name" >
												<template v-slot:prefix>
													<uv-text
														text="名称"
														margin="0 10px 0 0"
														type="tips"
													></uv-text>
												</template>
											</uv-input>
                                            <uv-input placeholder="链接" class="d-shang-10"  border="surround" v-model="item.url" >
												<template v-slot:prefix>
													<uv-text
														text="链接"
														margin="0 10px 0 0"
														type="tips"
													></uv-text>
												</template>
											</uv-input>
                                        </view>
                                    </view>

                                </view>
								<uv-button  class="d-shang-10" type="primary" text="确 认" @click="postUrl_data_api"></uv-button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </uv-overlay>
    </view>
</template>

<script>
import UrlApi from '@/utils/url_api.js';
import { postRequest } from '@/utils/wxRequest';
export default {
	props: {
		url_data_show: {
			type: Boolean,
			default: false
		},
		tieid: {
		  type: [String, Number],
		  default: ''
		},
		quanid: {
		  type: [String, Number],
		  default: ''
		},
        url_data_list: {
            type: Array,
            default: () => []
        }
	},
	data() {
		return {
            url_data_add: [
                {
                    name: '',
                    url: '',
                }
            ],
            url_data_add_index: 0,
            url_data_add_obj: {}
        }
    },
	watch: {
        // 监听组件显示状态变化，当显示时触发检测接口
        'url_data_show': function(newVal) {
	    	if (newVal) {
	    		// 处理嵌套对象结构的数据
	    		if (this.url_data_list && this.url_data_list.length > 0 && typeof this.url_data_list[0] === 'object') {
	    			// 检查是否是嵌套结构: [{"1":{"name":"","url":""}}]
	    			const firstItem = this.url_data_list[0];
	    			const hasNumericKey = Object.keys(firstItem).some(key => !isNaN(key));
	    			
	    			if (hasNumericKey) {
	    				// 转换嵌套结构为扁平数组
	    				const flattenedList = [];
	    				for (const item of this.url_data_list) {
	    					for (const key in item) {
	    						if (item[key] && typeof item[key] === 'object') {
	    							flattenedList.push(item[key]);
	    						}
	    					}
	    				}
	    				this.url_data_add = flattenedList;
	    			} else {
	    				this.url_data_add = this.url_data_list;
	    			}
	    		} else {
	    			this.url_data_add = this.url_data_list || [{ name: '', url: '' }];
	    		}
	    	}
	    }
	},
	methods: {
		url_close_get() {
			//this.url_data_show = false;
			this.$emit('url_close_get', false);
		},
		// 添加url组
		url_tianjia() {
		  // 添加一个新的创业金组对象到数组中
		  this.url_data_add.push({
			name: '',
			url: '',
		  });
		  
		  // 滚动到底部，确保新增的组可见
		  this.$nextTick(() => {
			const scrollView = document.getElementById('d-gundong');
			if (scrollView) {
			  scrollView.scrollTop = scrollView.scrollHeight;
			}
		  });
		},
		// 删除url组
		url_shanchu(index) {
		  // 直接删除指定索引的URL组，不保留任何一组
		  this.url_data_add.splice(index, 1);
		},
		// 提交url数据
		async postUrl_data_api() {
			// 验证URL列表不为空
			if (this.url_data_add.length == 0) {
				uni.showToast({
					title: '请添加链接',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			// 验证每个URL的name和url字段都不为空
			const hasEmptyField = this.url_data_add.some(item => {
				return !item.name || item.name.trim() === '' || !item.url || item.url.trim() === '';
			});
			
			if (hasEmptyField) {
				uni.showToast({
					title: '请填写完整链接信息',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			
			// 创建指定格式的对象
			let urlFormatObj = {};
			this.url_data_add.forEach((item, index) => {
			  // 使用索引+1作为外层对象的键
			  urlFormatObj[index + 1] = {
			    name: item.name || '', // name 对应键1
			    url: item.url || '', // url 对应键2
			  };
			});
			let urlJson = JSON.stringify(urlFormatObj);
			// 构建请求数据
            // 注意：url_data_add是数组，没有title属性，这里使用第一个链接的名称作为title
            var title = this.url_data_add.length > 0 ? this.url_data_add[0].name : '';
			var id_data = '&data[quanid]='+this.quanid+'&data[tieid]='+this.tieid;
            var datas = "is_ajax=1&data[title]="+encodeURIComponent(title)+"&data[url]="+encodeURIComponent(urlJson)+id_data;

			let uid = this.$store.state.memberuid;
            let code = this.$store.state.keycode;
            let url = UrlApi.editUrl(uid,code,this.tieid,this.quanid);
			let res = await postRequest(url,datas);
			 if(res.data.code==1){
 				  uni.showToast({
 				    title: '添加成功',
 				    icon: 'success',
 				    duration: 2000
 				  });
 				  
 				} else {
 				  uni.showToast({
 				    title: res.data.msg,
 				    icon: 'none',
 				    duration: 2000
 				  });
 				}
 				// 请求完成后关闭对话框
 				this.url_close_get();
 				// 触发父组件更新数据
 				this.$emit('refreshData');
			},
			// 更新URL数据的通用方法
	},
	mounted() {
		// 组件
		
	},
}
</script>

<style>
.warp_url {
	display: flex;
	align-items: center;
	justify-content: center;
	height: 100%;
}
.rect_url {
	width: 300px;
	height: 400px;
	padding: 10px;
	background-color: #fff;
	border-radius: 10px;
}
.d-url-gao {
    height: 1000rpx;
    overflow: auto;
}
#d-gundong {
  max-height: 250px; /* 设置最大高度，超出部分将滚动 */
  overflow-y: auto; /* 允许垂直方向滚动 */
  padding-right: 5px; /* 为滚动条留出空间 */
}

/* 自定义滚动条样式（可选） */
#d-gundong::-webkit-scrollbar {
  width: 6px;
}

#d-gundong::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

#d-gundong::-webkit-scrollbar-thumb {
  background: #888;
  border-radius: 3px;
}

#d-gundong::-webkit-scrollbar-thumb:hover {
  background: #555;
}
</style>